<!-- 授信管理--额度管理 -->
<template>
  <div>
    <PlusPage
      :columns="pageConfig"
      :table="{
        adaptive: true,
        hasIndexColumn: true,
        actionBar: { buttons, width: 140 },
      }"
      :default-page-info="{ pageSize: DEFAULT_PAGE_SIZE, page: 1 }"
      :request="getList"
    >
      <!-- 表格标题 -->
      <template #table-title>
        <!-- 同步 -->
        <el-button type="primary" :loading="syncLoading" @click="onSyncBankResult">同步</el-button>
      </template>
    </PlusPage>
  </div>
</template>

<script lang="ts" setup>
import type { BasePageReq } from '@wlydfe/service'
import type { LimitModel } from '@/api/type'
import { getOptionLabel, priceToThousands } from '@wlydfe/core'
import {
  type ButtonsCallBackParams,
  type PageInfo,
  type PlusColumn,
  useTable,
} from '@wlydfe/pro-ui'
import { ElMessage } from 'element-plus'
import { omit } from 'lodash-es'
import { creditmanageApi } from '@/api'
import { useEnum } from '@/composables/enum/useEnum'

const router = useRouter()
const enumConfig = useEnum([CommonDictEnum.NEWEDZTLX])
const syncLoading = ref(false)
const DEFAULT_PAGE_SIZE = 20
const queryParams = ref<BasePageReq<Partial<LimitModel>>>({
  currentPage: 1,
  pageLength: DEFAULT_PAGE_SIZE,
  countTotal: true,
  filterModel: {},
})
const getList = async (query: Partial<PageInfo> & Partial<LimitModel>) => {
  // 构造查询参数
  queryParams.value.currentPage = query.page ?? 1
  queryParams.value.pageLength = query.pageSize ?? DEFAULT_PAGE_SIZE
  queryParams.value.filterModel = omit(query, ['page', 'pageSize', 'value'])
  if (Array.isArray(query.startDate)) {
    queryParams.value.filterModel.beginStartDate = query.startDate[0]
    queryParams.value.filterModel.endStartDate = query.startDate[1]
    delete queryParams.value.filterModel.startDate
  }

  if (Array.isArray(query.endDate)) {
    queryParams.value.filterModel.beginEndDate = query.endDate[0]
    queryParams.value.filterModel.endEndDate = query.endDate[1]
    delete queryParams.value.filterModel.endDate
  }
  const { succeed, model, total } = await creditmanageApi.getLimitWlist(queryParams.value)
  return {
    data: succeed ? model : [],
    total: total ?? 0,
  }
}

const onSyncBankResult = async () => {
  if (syncLoading.value) {
    return
  }
  syncLoading.value = true
  const { succeed } = await creditmanageApi.getRefresh()
  if (succeed) {
    ElMessage.success('同步成功')
    syncLoading.value = false
  } else {
    ElMessage.error('同步失败')
    syncLoading.value = false
  }
}

const pageConfig: PlusColumn[] = [
  {
    label: '额度编号',
    prop: 'limitNo',
    renderHeader: () => '授信编号',
    hideInSearch: false,
    order: 4,
  },
  {
    label: '企业名称',
    prop: 'companyName',
    hideInSearch: false,
    order: 6,
  },
  {
    label: '金融机构',
    prop: 'financialInstitution',
    hideInSearch: false,
    order: 5,
  },
  {
    label: '金融产品',
    prop: 'financialProductType',
    render: (value, { row }) => {
      return row.financialProductType && row.financialInstitution === '南京银行股份有限公司'
        ? getOptionLabel(financialProductTypeOptions, value)
        : '-'
    },
  },
  {
    label: '授信总额度（元）',
    prop: 'totalAmt',
    render: value => {
      return priceToThousands(value)
    },
  },
  {
    label: '已用额度（元）',
    prop: 'usedAmt',
    render: value => {
      return priceToThousands(value)
    },
  },
  {
    label: '可用额度（元）',
    prop: 'usableAmt',
    render: value => {
      return priceToThousands(value)
    },
  },
  {
    label: '冻结额度（元）',
    prop: 'freezeAmt',
    render: value => {
      return priceToThousands(value)
    },
  },
  {
    label: '起始日期',
    prop: 'startDate',
    hideInSearch: false,
    valueType: 'date-picker',
    fieldProps: {
      type: 'datetimerange',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      rangeSeparator: '至',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    order: 2,
  },
  {
    label: '到期日期',
    prop: 'endDate',
    hideInSearch: false,
    valueType: 'date-picker',
    fieldProps: {
      type: 'datetimerange',
      startPlaceholder: '开始时间',
      endPlaceholder: '结束时间',
      rangeSeparator: '至',
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
    order: 1,
  },
  {
    label: '额度状态',
    prop: 'status',
    hideInSearch: false,
    valueType: 'select',
    options: enumConfig[CommonDictEnum.NEWEDZTLX],
    order: 3,
  },
]
const { buttons } = useTable()
// 按钮
buttons.value = [
  {
    text: '查看',
    code: 'view',
    props: { type: 'primary' },
    onClick(params: ButtonsCallBackParams) {
      if (params?.row) {
        router.push({
          path: '/creditCenter/quotaManagement/detail',
          query: { id: params.row.id },
        })
        console.log(params.row, 'params.row')
      }
    },
  },
]
</script>
